#import "Utils.h"
#import <SystemConfiguration/SystemConfiguration.h>
#import <netinet/in.h>
#import <CommonCrypto/CommonDigest.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import <CoreTelephony/CTCellularData.h>
#import <CoreLocation/CoreLocation.h>

@implementation Utils

/**
 * 生成UUID
 * @return 返回一个小写的UUID字符串
 */
+ (NSString *)uuid {
    CFUUIDRef puuid = CFUUIDCreate(nil);
    CFStringRef uuidString = CFUUIDCreateString(nil, puuid);
    NSString *result = (NSString *)CFBridgingRelease(CFStringCreateCopy(NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    result = [result lowercaseString];
    return result;
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"

/**
 * 判断是否开启推送
 * @return 返回一个布尔值，如果开启了推送返回YES，否则返回NO
 */
+ (BOOL)isNotifyAlert {
    UIUserNotificationType types = [[UIApplication sharedApplication] currentUserNotificationSettings].types;
    BOOL isNotifyAlert = (types & UIUserNotificationTypeAlert) == UIUserNotificationTypeAlert;
    return isNotifyAlert;
}

/**
 * 获取当前时间戳
 * @return 返回一个格式化的时间戳字符串
 */
+ (NSString *)timeStamp {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *newDateString = [formatter stringFromDate:[NSDate date]];
    return newDateString;
}

/**
 * 返回从 UTC 1970 年 1 月 1 日午夜开始经过的毫秒数
 * @return 返回一个长整型的毫秒数
 */
+ (long long)currentTimeMillis {
    return [[NSDate date] timeIntervalSince1970] * 1000;
}

/**
 * 根据给定的16进制颜色字符串和透明度生成UIColor对象
 * @param color 16进制颜色字符串
 * @param alpha 透明度
 * @return 返回一个UIColor对象
 */
+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha {
    //删除字符串中的空格
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    //String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    //strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) {
        cString = [cString substringFromIndex:2];
    }
    if ([cString hasPrefix:@"#"]) {
        cString = [cString substringFromIndex:1];
    }
    if ([cString length] != 6) {
        return [UIColor clearColor];
    }

    //Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    //r
    NSString *rString = [cString substringWithRange:range];
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    //扫描值
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float)r / 255.0f) green:((float)g / 255.0f) blue:((float)b / 255.0f) alpha:alpha];
}

/**
 * 使用默认的alpha值为1，将十六进制颜色字符串转换为UIColor对象
 * @param color 十六进制颜色字符串
 * @return 返回一个UIColor对象
 */
+ (UIColor *)colorWithHexString:(NSString *)color {
    return [self colorWithHexString:color alpha:1.0f];
}

/**
 * 将UIColor对象转换为#ffffff格式的字符串
 * @param color UIColor对象
 * @return 返回一个#ffffff格式的字符串
 */
+ (NSString *)hexStringFromColor:(UIColor *)color {
    const CGFloat *components = CGColorGetComponents(color.CGColor);

    CGFloat r = components[0];
    CGFloat g = components[1];
    CGFloat b = components[2];

    return [NSString stringWithFormat:@"#%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255)];
}

/**
 * 将UIColor对象转换为RGB数组
 * @param color UIColor对象
 * @return 返回一个包含RGB值的数组
 */
+ (NSArray *)colorRGBFromColor:(UIColor *)color {
    const CGFloat *components = CGColorGetComponents(color.CGColor);

    CGFloat r = components[0];
    CGFloat g = components[1];
    CGFloat b = components[2];

    return [NSArray arrayWithObjects:@(lroundf(r * 255)), @(lroundf(g * 255)), @(lroundf(b * 255)), nil];
}

/**
 * 获取应用版本号
 * @return 返回应用版本号
 */
+ (NSString *)appVersion {
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *marketingVersionNumber = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    return marketingVersionNumber;
}

/**
 * 获取应用的bundle identifier
 * @return 返回应用的bundle identifier
 */
+ (NSString *)bundleIdentifier {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
}

/**
 * 获取当前设备使用的语言
 * @return 返回当前设备使用的语言
 */
+ (NSString *)getPreferredLanguage {
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    NSArray *languages = [defs objectForKey:@"AppleLanguages"];
    NSString *preferredLang = [languages objectAtIndex:0];
    return preferredLang;
}

/**
 * 获取设备的分辨率
 * @return 返回设备的分辨率
 */
+ (NSString *)resolution {
    CGSize screen_Size = [UIScreen mainScreen].bounds.size;

    CGFloat scren_scale = [UIScreen mainScreen].scale;

    return [NSString stringWithFormat:@"%.fx%.f", screen_Size.width * scren_scale, screen_Size.height * scren_scale];
}

/**
 * 获取系统版本
 * @return 返回系统版本
 */
+ (NSString *)osVersion {
    return [UIDevice currentDevice].systemVersion;
}

/**
 * 获取设备名称
 * @return 返回设备名称
 */
+ (NSString *)deviceName {
    struct utsname systemInfo;

    uname(&systemInfo);

    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];

    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";

    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";

    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";

    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";

    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";

    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";

    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";

    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";

    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";

    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";

    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";

    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";

    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";

    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";

    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";

    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";

    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";

    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";

    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";

    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";

    return @"iPhone";
}

/**
 * 判断iPhone是否联网状态
 * @return 返回一个布尔值，表示iPhone是否联网
 */
+ (BOOL)isNetworkReachable {
    //Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    //Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;

    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);

    if (!didRetrieveFlags) {
        return NO;
    }

    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    return (isReachable && !needsConnection) ? YES : NO;
}

/**
 * 获取网络类型
 * @return 返回一个字符串，表示网络类型
 */
+ (NSString *)netType {
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
    NSNumber *dataNetworkItemView = nil;

    for (id subview in subviews) {
        if ([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
            dataNetworkItemView = subview;
            break;
        }
    }

    NSString *netType = @"";
    NSNumber *num = [dataNetworkItemView valueForKey:@"dataNetworkType"];
    if (num == nil) {
        netType = @"";

    } else {
        int n = [num intValue];
        //NSLog(@"dataNetworkType:%d",n);
        if (n == 0) {
            netType = @"";
        } else if (n == 1) {
            netType = @"2g";
        } else if (n == 2) {
            netType = @"3g";
        } else if (n == 3) {
            netType = @"4g";
        } else {
            netType = @"wifi";
        }
    }

    return netType;
}

/**
 * 根据格式化日期字符串获取星期字符串
 * @param string 格式化日期字符串
 * @return 返回一个星期字符串
 */
+ (NSString *)weekStringByFormatDateString:(NSString *)string {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //首先转为 NSDate
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [formatter setDateFormat:@"MM/dd/yyyy"];
    NSRange range = [string rangeOfString:@" "];
    NSDate *date = [formatter dateFromString:[string substringToIndex:range.location]];

    //转换为带星期的字符串
    [formatter setDateFormat:@"EEEE MM/dd/yyyy"];
    NSString *newDateString = [formatter stringFromDate:date];
    return newDateString;
}

/**
 * 根据格式化日期字符串获取日期字符串
 * @param string 格式化日期字符串
 * @return 返回一个日期字符串
 */
+ (NSString *)stringByFormatDateString:(NSString *)string {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //首先转为 NSDate
    [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
    NSRange range = [string rangeOfString:@" "];
    NSDate *date = [formatter dateFromString:[string substringToIndex:range.location]];

    //转换为带星期的字符串
    [formatter setDateFormat:@"MM/dd/yyyy"];
    NSString *newDateString = [formatter stringFromDate:date];
    return newDateString;
}

/** 颜色 */
#define BASE_BG_COLOR @"#ededed"
#define BASE_GREEN_COLOR @"#00b181"
#define BASE_LIGHT_GRAY_COLOR @"b3b3b3"
#define BASE_GRAY_COLOR @"b2b2b2"
#define BASE_DARK_COLOR @"000000"

//创建导航条
/**
 * 创建导航条
 * @param title 导航条标题
 * @param left 左侧按钮标题
 * @param right 右侧按钮标题
 * @param sel 目标对象
 * @return 返回一个导航条视图
 */
+ (UIView *)createTitleView:(NSString *)title leftName:(NSString *)left rightName:(NSString *)right target:(id)sel {
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    //标题背景
    titleView.backgroundColor = [self colorWithHexString:BASE_BG_COLOR];
    UILabel *linerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 43, 320, 1)];
    [linerLabel setBackgroundColor:[UIColor clearColor]];
    [titleView addSubview:linerLabel];
    //图片
    UIImageView *leftRedArrow = [[UIImageView alloc] initWithFrame:CGRectMake(10, 11, 21, 21)];
    [leftRedArrow setImage:[UIImage imageNamed:@"left_back_arr.png"]];
    [titleView addSubview:leftRedArrow];
    //返回按钮
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setFrame:CGRectMake(leftRedArrow.frame.origin.x + 13, 0, 44, 44)];
    [backBtn setTitle:left forState:UIControlStateNormal];
    [backBtn.titleLabel setTextColor:[self colorWithHexString:BASE_GREEN_COLOR]];
    backBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    backBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    [backBtn setTitleColor:[self colorWithHexString:BASE_GREEN_COLOR] forState:UIControlStateNormal];
    //[backBtn addTarget:sel action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:backBtn];
    if ([title length] > 0) {
        CGFloat titlelength = [self caculateTextLengt:title FontSize:18 withWidth:1000 WithHight:21];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(320 / 2 - titlelength / 2, 11, titlelength, 21)];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        [titleLabel setText:title];
        [titleLabel setTag:101];
        [titleLabel setFont:[UIFont systemFontOfSize:17]];
        [titleView addSubview:titleLabel];
    }
    //根据标题长度改变宽
    if ([right length] > 0) {
        CGFloat rightlength = [self caculateTextLengt:right FontSize:17 withWidth:1000 WithHight:21];
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [rightBtn setFrame:CGRectMake(305 - rightlength, 0, 44, 44)];
        [rightBtn setTitle:right forState:UIControlStateNormal];
        rightBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        [rightBtn.titleLabel setTextColor:[self colorWithHexString:BASE_GREEN_COLOR]];
        [rightBtn setTitleColor:[self colorWithHexString:BASE_GREEN_COLOR] forState:UIControlStateNormal];
        //[rightBtn addTarget:sel action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:rightBtn];
        [rightBtn setTag:9002];
    }

    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, titleView.frame.size.height - 1, titleView.frame.size.width, 1)];
    v.backgroundColor = [self colorWithHexString:BASE_GRAY_COLOR];
    [titleView addSubview:v];

    return titleView;
}

/**
 * 计算文本长度
 * @param text 文本内容
 * @param fontsize 字体大小
 * @param width 宽度
 * @param hight 高度
 * @return 返回文本长度
 */
+ (CGFloat)caculateTextLengt:(NSString *)text FontSize:(CGFloat)fontsize withWidth:(CGFloat)width WithHight:(CGFloat)hight {
    UIFont *font = [UIFont systemFontOfSize:fontsize];
    CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(width, hight) lineBreakMode:NSLineBreakByWordWrapping];
    return size.width;
}

/**
 * 根据日期字符串获取日期
 * @param dateString 日期字符串
 * @return 返回一个日期
 */
+ (NSDate *)dateFromString:(NSString *)dateString {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    //[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate *destDate = [dateFormatter dateFromString:dateString];

    return destDate;
}

/**
 * 根据时间戳获取日期字符串
 * @param time 时间戳
 * @return 返回一个日期字符串
 */
+ (NSString *)stringFromTimeMillis:(NSTimeInterval)time {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time / 1000.0];

    NSString *destDateString = [dateFormatter stringFromDate:date];

    return destDateString;
    //return [TimeUtil stringByFormatTimeString:destDateString];
}

/**
 * 根据时间戳和格式获取日期字符串
 * @param time 时间戳
 * @param formatter 日期格式
 * @return 返回一个日期字符串
 */
+ (NSString *)stringFromTimeMillis:(NSTimeInterval)time formatter:(NSString *)formatter {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [dateFormatter setDateFormat:formatter];

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time / 1000.0];

    NSString *destDateString = [dateFormatter stringFromDate:date];

    return destDateString;
    //return [TimeUtil stringByFormatTimeString:destDateString];
}

/**
 * 根据日期获取日期字符串
 * @param date 日期
 * @return 返回一个日期字符串
 */
+ (NSString *)stringFromDate:(NSDate *)date {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    //[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSString *destDateString = [dateFormatter stringFromDate:date];

    return destDateString;
}

/**
 * 根据日期和格式获取日期字符串
 * @param date 日期
 * @param formatter 日期格式
 * @return 返回一个日期字符串
 */
+ (NSString *)stringFromDate:(NSDate *)date formatter:(NSString *)formatter {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [dateFormatter setDateFormat:formatter];
    NSString *destDateString = [dateFormatter stringFromDate:date];

    return destDateString;
}

/**
 * 将英文星期转换为中文星期
 * @param en 英文星期
 * @return 返回中文星期
 */
+ (NSString *)convertDay:(NSString *)en {
    if ([en containsString:@"Monday"]) {
        en = [en stringByReplacingOccurrencesOfString:@"Monday" withString:@"星期一"];
    } else if ([en containsString:@"Tuesday"]) {
        en = [en stringByReplacingOccurrencesOfString:@"Tuesday" withString:@"星期二"];
    } else if ([en containsString:@"Wednesday"]) {
        en = [en stringByReplacingOccurrencesOfString:@"Wednesday" withString:@"星期三"];
    } else if ([en containsString:@"Thursday"]) {
        en = [en stringByReplacingOccurrencesOfString:@"Thursday" withString:@"星期四"];
    } else if ([en containsString:@"Friday"]) {
        en = [en stringByReplacingOccurrencesOfString:@"Friday" withString:@"星期五"];
    } else if ([en containsString:@"Saturday"]) {
        en = [en stringByReplacingOccurrencesOfString:@"Saturday" withString:@"星期六"];
    } else if ([en containsString:@"Sunday"]) {
        en = [en stringByReplacingOccurrencesOfString:@"Sunday" withString:@"星期日"];
    }

    return en;
}

/**
 * 将图片转换为圆形图片
 * @param image 原始图片
 * @param inset 内边距
 * @return 返回圆形图片
 */
+ (UIImage *)circleImage:(UIImage *)image withParam:(CGFloat)inset {
    UIGraphicsBeginImageContext(image.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2);
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGRect rect = CGRectMake(inset, inset, image.size.width - inset * 2.0f, image.size.height - inset * 2.0f);
    CGContextAddEllipseInRect(context, rect);
    CGContextClip(context);

    [image drawInRect:rect];
    CGContextAddEllipseInRect(context, rect);
    CGContextStrokePath(context);
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newimg;
}

/**
 * 根据颜色和大小生成一张图片
 * @param color 颜色
 * @param size 大小
 * @return 返回一张图片
 */
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0, 0, size.width, size.height);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);

    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}

/**
 * 创建一个带标题的导航返回按钮
 * @param title 按钮标题
 * @return 返回一个按钮
 */
+ (UIButton *)navBackButtonItemWithTitle:(NSString *)title {
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 80.0f, 30.0f);
    [backButton setImage:[UIImage imageNamed:@"left_back_arr.png"] forState:UIControlStateNormal];
    [backButton setImageEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
    [backButton setTitle:title forState:UIControlStateNormal];
    return backButton;
}

/**
 * 格式化文件大小
 * @param size 文件大小
 * @return 返回格式化后的文件大小
 */
+ (NSString *)formattedFileSize:(unsigned long long)size {
    NSString *formattedStr = nil;
    if (size == 0)
        formattedStr = @"0B";
    else if (size > 0 && size < 1024)
        formattedStr = [NSString stringWithFormat:@"%quB", size];
    else if (size >= 1024 && size < pow(1024, 2))
        formattedStr = [NSString stringWithFormat:@"%.1fKB", (size / 1024.)];
    else if (size >= pow(1024, 2) && size < pow(1024, 3))
        formattedStr = [NSString stringWithFormat:@"%.1fMB", (size / pow(1024, 2))];
    else if (size >= pow(1024, 3))
        formattedStr = [NSString stringWithFormat:@"%.1fGB", (size / pow(1024, 3))];

    return formattedStr;
}

/**
 * 判断是否是家长版本
 * @return 返回是否是家长版本
 */
+ (BOOL)isParentsVersion {
    NSString *appId = [self bundleIdentifier];
    if ([appId isEqualToString:@"com.isoftston.Chunlei"] || [appId isEqualToString:@"com.chunlei8.xx.parents"]) {  //||[appId isEqualToString:@"com.isoftstone.MIS"]
        return YES;
    }
    return NO;
}

/**
 * 截取字符串到指定长度
 * @param text 原始字符串
 * @param maxLength 最大长度
 * @return 返回截取后的字符串
 */
+ (NSString *)substringInMaxLength:(NSString *)text maxLength:(NSInteger)maxLength {
    NSUInteger asciiLength = 0;
    NSInteger idx = 0;
    for (NSUInteger i = 0; i < text.length; i++) {
        unichar uc = [text characterAtIndex:i];
        asciiLength += isascii(uc) ? 1 : 2;
        if (asciiLength >= maxLength) {
            idx = i;
            if (asciiLength == maxLength) {
                idx = i + 1;
            }
            break;
        }
    }
    return [text substringToIndex:idx];
}

#pragma mark - 检测字符长度

/**
 * 计算字符串的unicode长度
 * @param text 字符串
 * @return 返回字符串的unicode长度
 */
+ (NSUInteger)unicodeLengthOfString:(NSString *)text {
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < text.length; i++) {
        unichar uc = [text characterAtIndex:i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    return asciiLength;
}

/**
 * 验证邮箱
 * @param email 邮箱
 * @return 返回是否是有效的邮箱
 */
+ (BOOL)validateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

/**
 * 验证传真号码
 * @param fax 传真号码
 * @return 返回是否是有效的传真号码
 */
+ (BOOL)validateFax:(NSString *)fax {
    NSString *faxRegex = @"((\\d{11})|^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$)";
    NSPredicate *faxPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", faxRegex];
    return [faxPredicate evaluateWithObject:fax];
}

/**
 * 验证字符串是否只包含数字、字母、中文、下划线和减号
 * @param string 待验证的字符串
 * @return 返回是否符合条件
 */
+ (BOOL)validateNoCharacterChar:(NSString *)string {
    NSString *regex = @"^[A-Za-z0-9\u4e00-\u9fa5_-]+$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:string];
}

/**
 * 验证字符串是否为数字或浮点数
 * @param string 待验证的字符串
 * @return 返回是否为数字或浮点数
 */
+ (BOOL)validateNumberOrFloatText:(NSString *)string {
    NSString *regex = @"^[0-9]+[.]{0,1}[0-9]{0,}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:string];
}

/**
 * 验证手机号码是否正确
 * @param phone 手机号码
 * @return 返回是否是有效的手机号码
 */
+ (BOOL)validatePhone:(NSString *)phone {
    if (!phone || phone.length != 11) return NO;

    NSString *phoneRegex = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:phone];
}

/**
 * 验证手机号码是否正确（第二种正则表达式）
 * @param phone 手机号码
 * @return 返回是否是有效的手机号码
 */
+ (BOOL)validatePhoneV2:(NSString *)phone {
    if (!phone || phone.length != 11) return NO;

    NSString *phoneRegex = @"^[1][0-9][0-9]{9}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:phone];
}

/**
 * 验证QQ号码是否正确
 * @param QQ QQ号码
 * @return 返回是否是有效的QQ号码
 */
+ (BOOL)validateQQ:(NSString *)QQ {
    if (!QQ) return NO;
    NSString *QQRegex = @"[1-9][0-9]{4,}";
    NSPredicate *QQPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", QQRegex];
    return [QQPredicate evaluateWithObject:QQ];
}

/**
 * 验证字符串是否只包含数字
 * @param string 待验证的字符串
 * @return 返回是否只包含数字
 */
+ (BOOL)isNumberText:(NSString *)string {
    NSString *regex = @"^[0-9]*$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}

/**
 * 验证密码是否符合6-16位数字和字母组合
 * @param psw 密码
 * @return 返回是否符合密码规则
 */
+ (BOOL)validatePsw:(NSString *)psw {
    if (!psw) return NO;

    NSString *regex = @"(?!^[0-9]+$)(?!^[a-zA-Z]+$)[0-9a-zA-Z]{6,16}";

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:psw];
}

/**
 * 验证昵称是否有效
 * @param nickName 昵称
 * @return 返回是否是有效的昵称
 */
+ (BOOL)validateNickName:(NSString *)nickName {
    if (!nickName) return NO;

    NSString *regex = @"^[\u4E00-\u9FA50-9a-zA-Z-_]{1,20}$";

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:nickName];
}

/**
 * 验证文本是否有效
 * @param text 文本
 * @return 返回是否是有效的文本
 */
+ (BOOL)validateText:(NSString *)text {
    if (!text) return NO;

    NSString *regex = @"^[\u4E00-\u9FA50-9a-zA-Z-_]$";

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:text];
}

/**
 * 判断字符串中是否包含表情符号
 * @param string 字符串
 * @return 返回是否包含表情符号
 */
+ (BOOL)stringContainsEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                              const unichar hs = [substring characterAtIndex:0];
                              if (0xd800 <= hs && hs <= 0xdbff) {
                                  if (substring.length > 1) {
                                      const unichar ls = [substring characterAtIndex:1];
                                      const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                      if (0x1d000 <= uc && uc <= 0x1f77f) {
                                          returnValue = YES;
                                      }
                                  }
                              } else if (substring.length > 1) {
                                  const unichar ls = [substring characterAtIndex:1];
                                  if (ls == 0x20e3) {
                                      returnValue = YES;
                                  }
                              } else {
                                  if (0x2100 <= hs && hs <= 0x27ff) {
                                      returnValue = YES;
                                  } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                      returnValue = YES;
                                  } else if (0x2934 <= hs && hs <= 0x2935) {
                                      returnValue = YES;
                                  } else if (0x3297 <= hs && hs <= 0x3299) {
                                      returnValue = YES;
                                  } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                      returnValue = YES;
                                  }
                              }
                            }];

    return returnValue;
}

/**
 * 验证身份证号码是否有效
 * @param IdCard 身份证号码
 * @return 返回是否是有效的身份证号码
 */
+ (BOOL)validateIdCard:(NSString *)IdCard {
    if (IdCard.length <= 0) return NO;

    NSString *regex = @"(^\\d{15}$)|(^\\d{17}([0-9]|X)$)";

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:IdCard];
}

/**
 * 验证真实姓名是否有效
 * @param realname 真实姓名
 * @return 返回是否是有效的真实姓名
 */
+ (BOOL)validateRealName:(NSString *)realname {
    if (realname.length <= 0) return NO;

    NSString *regex = @"^[\u4E00-\u9FA5a-zA-Z]{1,20}$";

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

    return [pred evaluateWithObject:realname];
}

/**
 * 判断字符串是否包含汉字
 * @param chineseChar 待检测的字符串
 * @return 返回是否包含汉字
 */
+ (BOOL)containsChineseCharacters:(NSString *)chineseChar {
    if (chineseChar.length <= 0) return NO;

    NSString *regex = @"^.*[\u4e00-\u9fa5].*$";

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

    return [pred evaluateWithObject:chineseChar];
}

/**
 * 验证联系方式是否有效
 * @param contact 联系方式
 * @return 返回是否是有效的联系方式
 */
+ (BOOL)validateContact:(NSString *)contact {
    if (contact.length <= 0) return NO;

    NSString *regex = @"^[0-9-_\\s]{1,50}$";

    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

    return [pred evaluateWithObject:contact];
}

/**
 * SHA512加密字符串
 * @param s 待加密的字符串
 * @return 返回加密后的字符串
 */
+ (NSString *)getSHA512String:(NSString *)s {
    const char *cstr = [s cStringUsingEncoding:NSUTF8StringEncoding];

    NSData *data = [NSData dataWithBytes:cstr length:s.length];

    uint8_t digest[CC_SHA512_DIGEST_LENGTH];

    CC_SHA512(data.bytes, (CC_LONG)data.length, digest);

    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];

    for (int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++) [output appendFormat:@"%02x", digest[i]];

    NSString *output1 = [[output uppercaseString] copy];

    return output1;
}

/**
 * 获取当前连接的WiFi名称
 * @return 返回当前连接的WiFi名称
 */
+ (NSString *)getConnecteWifiName {
    NSString *wifiName = nil;
    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();

    if (!wifiInterfaces) {
        return nil;
    }

    NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;

    for (NSString *interfaceName in interfaces) {
        CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));

        if (dictRef) {
            NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
            NSLog(@"network info -> %@", networkInfo);

            wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
            CFRelease(dictRef);
        }
    }
    CFRelease(wifiInterfaces);

    return wifiName;
}

/**
 * 判断当前App是否有访问相机的权限
 * @return 返回一个布尔值，表示当前App是否有访问相机的权限
 */
+ (BOOL)authWithCamera {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        return NO;
    }
    return YES;
}

/**
 * 获取相机权限
 * @return 返回一个布尔值，表示是否获取到相机权限
 */
- (BOOL)getCameraPermission {
    __block BOOL permission = NO;

    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo
                             completionHandler:^(BOOL granted) {
                               permission = granted;
                             }];
    return permission;
}

/**
 * 判断当前App是否有访问麦克风的权限
 * @return 返回一个布尔值，表示当前App是否有访问麦克风的权限
 */
+ (BOOL)authWithMic {
    AVAuthorizationStatus authStarus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (authStarus == AVAuthorizationStatusDenied || authStarus == AVAuthorizationStatusRestricted) {
        return NO;
    }
    return YES;
}

/**
 * 获取麦克风权限
 * @return 返回一个布尔值，表示是否获取到麦克风权限
 */
+ (BOOL)getMicPermission {
    __block BOOL permission = NO;

    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio
                             completionHandler:^(BOOL granted) {
                               permission = granted;
                             }];

    return permission;
}

/**
 * 判断当前App是否有访问照片的权限
 * @return 返回一个布尔值，表示当前App是否有访问照片的权限
 */
+ (BOOL)authWithPhoto {
    PHAuthorizationStatus phAuthor = [PHPhotoLibrary authorizationStatus];

    if (phAuthor == PHAuthorizationStatusRestricted || phAuthor == PHAuthorizationStatusDenied) {
        //NSString *tips = [NSString stringWithFormat:@"请在iPhone的“设置-隐私-照片”选项中，允许 %@ 访问你的照片",[self appName]];
        return NO;
    }
    return YES;
}

/**
 * 获取照片权限
 * @return 返回一个布尔值，表示是否获取到照片权限
 */
+ (BOOL)getPhotoPermission {
    __block BOOL permission = NO;

    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
      switch (status) {
          case PHAuthorizationStatusAuthorized:
          case PHAuthorizationStatusDenied:
              permission = NO;
              break;
          case PHAuthorizationStatusRestricted:
          case PHAuthorizationStatusNotDetermined:
              permission = YES;
          case PHAuthorizationStatusLimited:
              break;
      }
    }];
    return permission;
}

/**
 * 判断当前App是否有联网权限
 * @return 返回一个布尔值，表示当前App是否有联网权限
 */
+ (BOOL)authWithNetwork {
    CTCellularData *cellularData = [CTCellularData new];

    __block BOOL hasPermission = NO;

    cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state) {
      switch (state) {
          case kCTCellularDataRestricted:  //受限
              hasPermission = NO;
              break;

          case kCTCellularDataNotRestricted:  //未受限
              hasPermission = YES;
              break;

          case kCTCellularDataRestrictedStateUnknown:
              //第一次请求
              hasPermission = YES;
              break;
      }
    };
    return hasPermission;
}

/**
 * 获取联网权限
 * @return 返回一个布尔值，表示是否获取到联网权限
 */
+ (BOOL)getNetworkPermission {
    __block BOOL hasPermission = NO;
    CTCellularData *cellularData = [CTCellularData new];
    CTCellularDataRestrictedState state = cellularData.restrictedState;
    switch (state) {
        case kCTCellularDataNotRestricted:
            hasPermission = YES;
            break;
        case kCTCellularDataRestricted:
            hasPermission = NO;
            break;
        case kCTCellularDataRestrictedStateUnknown:
            hasPermission = YES;
            break;
    }

    return hasPermission;
}

/**
 * 富文本转html字符串
 * @param string 富文本字符串
 * @return 返回一个html字符串
 */
+ (NSString *)attriToStrWithAttri:(NSString *)string {
    NSString *returnString = @"";
    returnString = [string stringByReplacingOccurrencesOfString:@"&lt" withString:@"<"];
    returnString = [returnString stringByReplacingOccurrencesOfString:@"&gt" withString:@">"];

    NSLog(@"returnString: %@", returnString);
    return returnString;
}

/**
 * 字符串转富文本
 * @param htmlStr html字符串
 * @return 返回一个富文本对象
 */
+ (NSAttributedString *)strToAttriWithStr:(NSString *)htmlStr {
    return [[NSAttributedString alloc] initWithData:[htmlStr dataUsingEncoding:NSUnicodeStringEncoding]
                                            options:@{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType}
                                 documentAttributes:nil
                                              error:nil];
}

/**
 * 将对象转换为json字符串
 * @param object 任意对象
 * @return 返回一个json字符串
 */
+ (NSString *)convertToJsonData:(id)object {
    NSError *error;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0, jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0, mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

    return mutStr;
}

/**
 * 将json字符串转换为对象
 * @param jsonString json字符串
 * @return 返回一个对象
 */
+ (id)objectWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    id object = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if (err) {
        NSLog(@"json解析失败：%@", err);
        return nil;
    }
    return object;
}

/**
 * 获取当前window
 * @return 返回当前window
 */
+ (UIWindow *)mainWindow {
    UIApplication *app = [UIApplication sharedApplication];
    if ([app.delegate respondsToSelector:@selector(window)]) {
        return [app.delegate window];
    } else {
        return [app keyWindow];
    }
}

/**
 * 检查位置权限
 * @param vc 当前视图控制器
 * @param message 提示信息
 */
+ (void)checkLocationPermission:(UIViewController *)vc message:(NSString *)message {
    NSLog(@"---------------------- 要检查权限了 ----------------------");
    if (@available(iOS 13.0, *)) {
        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
            NSLog(@"---------------------- 权限被拒绝 ----------------------");
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
                                                                style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction *action) {
                                                              }]];
            [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
                                                                style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction *action) {
                                                                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                                                                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                                                                    [[UIApplication sharedApplication] openURL:url];
                                                                }
                                                              }]];
            [vc presentViewController:alertController animated:YES completion:nil];
        }
        NSLog(@"---------------------- 权限啊 ----------------------");
        CLLocationManager *locationManager = [[CLLocationManager alloc] init];
        if (![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
            [locationManager requestWhenInUseAuthorization];
        }
    }
}

#pragma clang diagnostic pop

@end
